#include "clock.h"
#include "polar.h"
#include <xlib.h>
#include <img.h>
#include <stdlib.h>

#ifndef M_PI
#define M_PI 3.14159265
#endif

#define BORDER	10	/*distancia entre el borde del reloj y la pantalla*/
#define LEN		20	/*longitud de las lineas de las horas.*/

/*Longitudes de las agujas.*/
#define H_LEN	90
#define M_LEN	170
#define S_LEN	220


static imgT * screen = NULL;

static void drawArm(double angle, int len, colorT c);

void initClock( imgT  * s )
{
	screen = s;
}

void drawClock( void )
{
	int radius, i;
	double angle;
	pointT center;
	polarPointT polarStart, polarEnd;
	colorT colour;

	if(screen == NULL)
		return;


	/*Inicializo colores y coordenadas para el borde exterior.*/
	center.x = screen->w/2-screen->h/2+BORDER;
	center.y = BORDER;

	colour.r = 255;
	colour.g = colour.b = 0;

	drawCircle(screen, screen->h/2-BORDER, center, colour);


	/*Dibujo las rayas.*/
	colour.r = colour.g = colour.b = 255;
	center.x = screen->w/2;
	center.y = screen->h/2;

	for(i = 0; i < 12; i++)
	{
		angle = ((2*M_PI)/12)*i;
		polarStart.r = screen->h/2-2*BORDER-LEN;
		polarEnd.r = screen->h/2-2*BORDER;

		polarStart.t = polarEnd.t = angle;

		drawLine(screen, polar2cart(polarStart, center), polar2cart(polarEnd, center),colour);
	}

	return;

}

void drawHours(struct tm t)
{
	colorT colour;
	double angle;

	if(screen == NULL)
		return;

	colour.r = 255;
	colour.g = colour.b = 150;

	angle = (t.tm_hour%12)*((2*M_PI)/12)+M_PI/2;
	angle += ((2*M_PI)/12)*(t.tm_min/60.0);

	drawArm(angle, H_LEN, colour);
}

void drawMinutes(struct tm t)
{
	colorT colour;
	double angle;

	if(screen == NULL)
		return;

	colour.g = 255;
	colour.r = colour.b = 200;

	angle = t.tm_min*((2*M_PI)/60)+M_PI/2;
	angle += ((2*M_PI)/60)*(t.tm_sec/60.0);

	drawArm(angle, M_LEN, colour);
}

void drawSeconds(struct tm t)
{
	colorT colour;
	double angle;

	if(screen == NULL)
		return;

	colour.b = 255;
	colour.r = colour.g = 100;

	angle = (t.tm_sec)*((2*M_PI)/60)+M_PI/2;

	drawArm(angle, S_LEN, colour);
}

void endClock( void )
{
	screen = NULL;
}

static void drawArm(double angle, int len, colorT c)
{
	pointT center;
	polarPointT polarStart, polarEnd;

	if(screen == NULL)
		return;

	center.x = screen->w/2;
	center.y = screen->h/2;

	polarStart.t = polarEnd.t = angle;
	polarStart.r = 0;
	polarEnd.r = len;

	drawLine(screen, polar2cart(polarStart, center), polar2cart(polarEnd, center),c);
}
